package com.yanh.merchant.controller;

import com.yanh.common.domain.PageResult;
import com.yanh.common.enums.ResultCode;
import com.yanh.common.exception.BusinessException;
import com.yanh.common.util.PhoneUtil;
import com.yanh.common.util.QRCodeUtil;
import com.yanh.merchant.domain.Merchant;
import com.yanh.merchant.dto.*;
import com.yanh.merchant.service.IFileService;
import com.yanh.merchant.service.IMerchantService;
import com.yanh.merchant.service.ISmsService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yanh
 * @since 2024-06-01
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/merchant")
@Tag(name="商户管理接口",description = "商户管理接口")
public class MerchantController {

    private final ISmsService smsService;
    private final IFileService fileService;
    private final IMerchantService merchantService;

    @Operation(summary ="获取手机验证码")
    @GetMapping("/sms")
    @Parameters(value = {@Parameter(name = "phone", description = "手机号", example = "1")})
    public String getSmsCode(@RequestParam("phone") String phone){
        //向验证码服务请求发送验证码
        return smsService.sendMsg(phone);
    }

    @Operation(summary ="上传证件照")
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile multipartFile) throws IOException {

        //调用fileService上传文件
        //生成的文件名称fileName，要保证它的唯一
        //文件原始名称
        String originalFilename = multipartFile.getOriginalFilename();
        //扩展名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")-1);
        //文件名称
        String fileName = UUID.randomUUID()+suffix;
        //byte[] bytes,String fileName
        return fileService.upload(multipartFile.getBytes(),fileName);
    }

    @Operation(summary ="商户注册")
    @PostMapping("/merchants/register")
    public boolean registerMerchant(@RequestBody MerchantRegisterDto merchantRegisterDto){

        if(StringUtils.isBlank(merchantRegisterDto.getMobile())){
            throw new BusinessException(ResultCode.PARAMETER_ILLEGAL.getMessage());
        }
        //手机号格式校验
        if(!PhoneUtil.isMatches(merchantRegisterDto.getMobile())){
            throw new BusinessException(ResultCode.PARAMETER_ILLEGAL.getMessage());
        }
        //校验验证码
        boolean smsBool=smsService.checkVerifiyCode(merchantRegisterDto.getMobile(),merchantRegisterDto.getVerifiyCode());
        if (!smsBool){
            throw new BusinessException(ResultCode.PARAMETER_ILLEGAL.getMessage());
        }
        //校验手机号的唯一性
        var mBool=merchantService.existMerchant(merchantRegisterDto.getMobile());
         if (mBool){
             throw new BusinessException(ResultCode.PARAMETER_ILLEGAL.getMessage());
         }
        //使用MapStruct转换对象
        Merchant merchant=new Merchant();
        merchant.setMobile(merchantRegisterDto.getMobile());
        merchant.setMerchantName(merchantRegisterDto.getMerchantName());
        merchant.setAuditStatus("0");
        return merchantService.createMerchant(merchant)>0;
    }

    @Operation(summary ="资质申请")
    @PostMapping("/my/merchants/apply")
    public void applyMerchant(@RequestBody MerchantDetailDto merchantInfo){
        merchantService.applyMerchant(merchantInfo);
    }

    @Operation(summary ="门店列表查询")
    @Parameters(value = {@Parameter(name = "phone", description = "手机号", example = "1"),
            @Parameter(name = "pageNo", description = "页码", example = "1"),
            @Parameter(name = "pageSize", description = "每页记录数", example = "1"),
    })
    @PostMapping("/my/stores/merchants/page")
    public PageResult<StoreDTO> queryStoreByPage(@RequestBody StoreDTO storeDTO, Integer pageNo, Integer pageSize){
//        //商户id
//        Long merchantId = SecurityUtil.getMerchantId();
        //查询条件
        storeDTO.setMerchantId(1L);//商户id
        //调用service查询列表
        PageResult<StoreDTO> storeDTOS = merchantService.queryStoreByPage(storeDTO, pageNo, pageSize);
        return storeDTOS;
    }


    @Operation(summary ="生成商户应用门店的二维码")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "appId", value = "商户应用id", required = true, dataType = "String", paramType = "path"),
//            @ApiImplicitParam(name = "storeId", value = "商户门店id", required = true, dataType = "String", paramType = "path"),
//    })
    @GetMapping(value = "/my/apps/{appId}/stores/{storeId}/app-store-qrcode")
    public String createCScanBStoreQRCode(@PathVariable("storeId") Long storeId, @PathVariable("appId")String appId) throws IOException {

        //获取商户id
//        Long merchantId = SecurityUtil.getMerchantId();
        Long merchantId = 1L;
        //商户信息
        MerchantDTO merchantDTO = merchantService.queryMerchantById(merchantId);

        QRCodeDto qrCodeDto = new QRCodeDto();
        qrCodeDto.setMerchantId(merchantId);
        qrCodeDto.setStoreId(storeId);
        qrCodeDto.setAppId(appId);
        //标题.用商户名称替换 %s
        String subjectFormat = String.format("", merchantDTO.getMerchantName());
        qrCodeDto.setSubject(subjectFormat);
        //内容
        String bodyFormat = String.format("", merchantDTO.getMerchantName());
        qrCodeDto.setBody(bodyFormat);

        //获取二维码的URL
        String storeQRCodeURL = merchantService.createStoreQRCodeUrl(qrCodeDto);

        //调用工具类生成二维码图片
        QRCodeUtil qrCodeUtil = new QRCodeUtil();
        //二维码图片base64编码
        String qrCode = qrCodeUtil.createQRCode(storeQRCodeURL, 200, 200);
        return qrCode;

    }

}
